package com.bh.web.controller.order;

import com.bh.common.annotation.Log;
import com.bh.common.core.controller.BaseController;
import com.bh.common.core.domain.AjaxResult;
import com.bh.common.core.page.TableDataInfo;
import com.bh.common.enums.BusinessType;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.poi.ExcelUtil;
import com.bh.extend.service.IJcOrderBarcodeService;
import com.bh.extend.vo.JcOrderBarcodePrintVo;
import com.bh.kysys.domain.JcSysOrganization;
import com.bh.kysys.service.IJcSysOrganizationService;
import com.bh.order.domain.JcOrder;
import com.bh.order.domain.JcOrderReceivingParty;
import com.bh.order.dto.JcAbnormalOrderDto;
import com.bh.order.dto.JcOrderQueryDto;
import com.bh.order.service.IJcOrderService;
import com.bh.order.vo.JcOrderCustVO;
import com.bh.order.vo.JcOrderImportVo;
import com.bh.order.vo.JcOrderRecheckVO;
import com.bh.order.vo.JcOrderVO;
import com.bh.system.service.ISysDictDataService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Controller
 *
 * @author slx
 * @date 2023-06-20
 */
@RestController
@RequestMapping("/order/order")
public class JcOrderController extends BaseController {
    @Autowired
    private IJcOrderService jcOrderService;

    @Autowired
    private IJcOrderBarcodeService jcOrderBarcodeService;

    @Autowired
    private IJcSysOrganizationService sysOrganizationService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(JcOrderQueryDto queryVo) {
        startPage();
        //会直接查询出发和到达的机构
        queryVo.setJcOrganizationId(getOrgId());
        List<JcOrderVO> list = jcOrderService.selectJcOrderVoList(queryVo);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/listStatistics")
    public AjaxResult listStatistics(JcOrderQueryDto queryVo) {
        //会直接查询出发和到达的机构
        queryVo.setJcOrganizationId(getOrgId());
        Map<String, Object> data = jcOrderService.selectJcOrderVoListStatistics(queryVo);
        return AjaxResult.success(data);
    }


    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单收入确认列表")
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/ledgerDetailList")
    public TableDataInfo ledgerDetailList(JcOrderQueryDto queryVo) {
        startPage();
        //会直接查询出发和到达的机构
        if(queryVo.getJcOrganizationId() == null) {
            queryVo.setJcOrganizationId(getOrgId());
        }
        List<JcOrderVO> list = jcOrderService.selectLedgerDetailList(queryVo);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, JcOrderQueryDto queryVo) {
        queryVo.setJcOrganizationId(getOrgId());
        List<JcOrderVO> list = jcOrderService.selectJcOrderVoList(queryVo);
        ExcelUtil<JcOrderVO> util = new ExcelUtil<>(JcOrderVO.class);
        util.exportExcel(response, list, "订单数据");
    }


    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportCust")
    public void exportCust(HttpServletResponse response, JcOrderQueryDto queryVo) {
        queryVo.setJcOrganizationId(getOrgId());
        List<JcOrderCustVO> list = jcOrderService.selectJcOrderCustVoList(queryVo);
        ExcelUtil<JcOrderCustVO> util = new ExcelUtil<>(JcOrderCustVO.class);
        util.exportExcel(response, list, "客户订单数据");
    }



    @Log(title = "订单导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('order:order:import')")
    @PostMapping("/importNewData")
    public AjaxResult importNewData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<JcOrderImportVo> util = new ExcelUtil<>(JcOrderImportVo.class);
        List<JcOrderImportVo> orderImportVos = util.importExcel(file.getInputStream());
        if (orderImportVos.size() > 500) {
            return error("请一次导入订单不要超过 500 条！");
        }
        Set<String> orgNames = orderImportVos.stream().map(JcOrderImportVo::getJcOrganizationIdName).collect(Collectors.toSet());
        if (orgNames.size() > 1) {
            return error("订单导入失败，同一个导入文件下不允许导入多个机构出发的数据！");
        }
        List<String> orgNameList = new ArrayList<>(orgNames);
        JcSysOrganization customerOrg = sysOrganizationService.selectJcSysOrganizationById(getOrgId());
        if (!orgNameList.getFirst().equals(customerOrg.getName())) {
            return error("订单导入失败，请使用当前选择的页面右上角机构为出发机构！");
        }
        String message = jcOrderService.importNewOrder(orderImportVos, updateSupport, getUsername());
        return success(message);
    }

    /**
     * 此处特殊
     *
     * @return
     */
    @PostMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<JcOrderImportVo> util = new ExcelUtil<>(JcOrderImportVo.class);
        AjaxResult ajaxResult = util.importTemplateExcel("订单数据导入模板");
        ajaxResult.put("fileName", ajaxResult.get("msg"));
        ajaxResult.put("msg", null);
        return ajaxResult;
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importNewTemplate")
    public void importNewTemplate(HttpServletResponse response) {
        ExcelUtil<JcOrderImportVo> util = new ExcelUtil<>(JcOrderImportVo.class);
        util.importTemplateExcel(response, "订单数据导入模板");
    }


    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(jcOrderService.selectJcOrderById(id));
    }

    /**
     * 新增订单
     */
    @ApiOperation("新增订单")
    @PreAuthorize("@ss.hasPermi('order:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody JcOrder jcOrder) {
        AjaxResult toAjax = toAjax(jcOrderService.insertJcOrder(jcOrder));
        toAjax.put("id", jcOrder.getId());
        return toAjax;
    }

    /**
     * 修改订单
     */
    @ApiOperation("修改订单")
    @PreAuthorize("@ss.hasPermi('order:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JcOrder jcOrder) {
        return toAjax(jcOrderService.updateJcOrder(jcOrder));
    }



    /**
     * 极其特殊情况下，修改订单错内容
     * @param abnormalOrderDto
     * @return
     */
    @PreAuthorize("@ss.hasPermi('order:order:abnormal')")
    @ApiOperation("极其特殊情况下，修改订单错内容")
    @PostMapping("/saveAbnormalJcOrder")
    public AjaxResult saveAbnormalJcOrder(@RequestBody JcAbnormalOrderDto abnormalOrderDto) {
        return toAjax(jcOrderService.saveAbnormalJcOrder(abnormalOrderDto.getJcOrder(), abnormalOrderDto.getAbnormal()));
    }

    /**
     * 复制订单
     * @param orderIds
     * @return
     */
    @PreAuthorize("@ss.hasPermi('order:order:copy')")
    @ApiOperation("复制订单")
    @PostMapping(value = "/copyOrders/{orderIds}")
    public AjaxResult copyOrders(@PathVariable Long[] orderIds) {
        return toAjax(jcOrderService.copyOrders(orderIds, getUsername()));
    }


    /**
     * 删除订单
     */
    @ApiOperation("删除订单")
    @PreAuthorize("@ss.hasPermi('order:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(jcOrderService.deleteJcOrderByIds(ids));
    }


    /**
     * 订单打印
     * @param ids
     * @return
     */
    @ApiOperation("订单打印")
    @PostMapping(value = "/getOrderPrint/{ids}")
    public AjaxResult getOrderPrint(@PathVariable("ids") Long[] ids) {
        List<Map<String, Object>> datas = new ArrayList<>();
        for (Long id : ids) {
            JcOrder order = jcOrderService.selectJcOrderById(id);
            Map<String, Object> result = new HashMap<>();
            result.put("relateBill1", order.getRelateBill1());
            result.put("relateBill2", order.getRelateBill2());
            result.put("code", order.getCode());
            result.put("time", DateUtils.formatDate(order.getTime(), "yyyy-MM-dd"));
            result.put("startOrg", order.getFromOrganization().getName());
            result.put("endOrg", order.getToOrganization().getName());
            result.put("endZone", order.getJcEndZoneIdName());
            result.put("remark", order.getDescription() == null ? "" : order.getDescription());
            List<JcOrderReceivingParty> orderReceivingParties = order.getOrderReceivingParties();
            for (JcOrderReceivingParty orderReceivingParty : orderReceivingParties) {
                if (orderReceivingParty.getType() == 0) {
                    result.put("FHF", orderReceivingParty);
                } else {
                    result.put("SHF", orderReceivingParty);
                }
            }
            List<JcOrderBarcodePrintVo> barcodes = jcOrderBarcodeService.selectJcOrderBarcodePrintVoListByOrderId(id);
            if (barcodes != null && !barcodes.isEmpty()) {
                // 将包装类型为冷藏箱的名称加(L)
                List<String> packageTypeList = Arrays.asList("21", "22", "23");
                barcodes = barcodes.stream().peek(orderBarcode -> {
                    if (packageTypeList.contains(orderBarcode.getPackageType())) {
                        orderBarcode.setProductName(orderBarcode.getProductName() + "(L)");
                    }
                }).collect(Collectors.toList());
            }
            if (barcodes != null && !barcodes.isEmpty()) {
                result.put("barcodes", barcodes);
            }
            result.put("number", order.getNumber());
            result.put("transportPro", sysDictDataService.selectJcDictLabelByType("TransportPro", order.getTransportPro().toString()));
            result.put("handoverType", sysDictDataService.selectJcDictLabelByType("HandoverType", order.getHandoverType().toString()));
            result.put("backNumber", order.getBackNumber());
            result.put("isBack", order.getIsBack());
            datas.add(result);
        }

        return AjaxResult.success(datas);
    }

    /**
     * 订单复核
     */
    @ApiOperation("订单复核")
    @PreAuthorize("@ss.hasPermi('order:order:recheck')")
    @PostMapping("/recheck")
    public AjaxResult review(@RequestBody JcOrderRecheckVO recheckVO) {
        return toAjax(jcOrderService.recheckOrder(recheckVO));
    }


    /**
     * 新增保存订单, 目前还没有使用
     */
    @ApiOperation("确认订单")
    @PreAuthorize("@ss.hasPermi('order:order:confirm')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm/{ids}")
    public AjaxResult confirmSave(@PathVariable("ids") String[] ids) {
        return toAjax(jcOrderService.confirmOrderSave(ids));
    }
}
